#include "proc_key.h"

my_key_t mkey[KEY_NUM]={0};

//硬件层接口 注意按键io和上下拉状态
u8 read_key_port(u8 n)
{
	switch(n){
		case 0:return HAL_GPIO_ReadPin(GPIOC,GPIO_PIN_4)?0:1;
		case 1:return HAL_GPIO_ReadPin(GPIOC,GPIO_PIN_5)?0:1;
		case 2:return HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0)?0:1;
		case 3:return HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_1)?0:1;
		case 4:return HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2)?0:1;
		case 5:return HAL_GPIO_ReadPin(GPIOC,GPIO_PIN_12)?0:1;
		default:break;
	}
	return 0;
}

//10ms调用一次 按键扫描
void key_scan(void)	
{
	u8 i;
	for(i=0;i<KEY_NUM;i++){
		mKey[i].count<<=1;
		mKey[i].count|=read_key_port(i);	
		if(mKey[i].flags.double_scan){				
			mKey[i].double_ticks_10ms++;
			if(mKey[i].double_ticks_10ms>=50){		
				mKey[i].flags.double_scan=0;
			}
		}
		if((mKey[i].count&0xFF)==0xFF){				
			mKey[i].flags.press=1;					
			mKey[i].long_ticks_10ms++;
			if(mKey[i].long_ticks_10ms>=100){		
				if(mKey[i].flags.lock_1s==0){
					mKey[i].flags.long_1s=1;			
					mKey[i].flags.lock_1s=1;						
				}
			}
			if(mKey[i].long_ticks_10ms>=200){		
				if(mKey[i].flags.lock_2s==0){
					mKey[i].flags.long_2s=1;			
					mKey[i].flags.lock_2s=1;						
				}
			}
			if(mKey[i].long_ticks_10ms>=600){		
				if(mKey[i].flags.lock_6s==0){
					mKey[i].flags.long_6s=1;			
					mKey[i].flags.lock_6s=1;						
				}
			}
		}
		else if(mKey[i].flags.press){				
			if(mKey[i].long_ticks_10ms<100){				
				if(mKey[i].flags.double_scan){		
					mKey[i].flags.key_double=1;
					mKey[i].flags.double_scan=0;
				}
				else{							
					mKey[i].flags.key_short=1;	
					mKey[i].flags.double_scan=1;
					mKey[i].double_ticks_10ms=0;
				}
			}
			mKey[i].flags.lock_1s=0;
			mKey[i].flags.lock_2s=0;
			mKey[i].flags.lock_6s=0;					
			mKey[i].flags.press=0;					
			mKey[i].long_ticks_10ms=0;
		}
	}
}

//按键处理 直接放主循环
void Task_key(void)
{
	u8 i;

	
	
	
	
	//清除所有标记
	for(i=0;i<KEY_NUM;i++){				//
		mKey[i].flags.key_short=0;
		mKey[i].flags.long_1s=0;
		mKey[i].flags.long_2s=0;
		mKey[i].flags.long_6s=0;
		mKey[i].flags.key_double=0;
	}
		
}




